const express = require("express");
const gravatar = require("gravatar");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const passport = require("passport");
const router = express.Router();

const keys = require("../config/keys");
const db = require("../config/db");
const sql = require("../config/sql").users;

// 查询所有用户
router.get("/allUser/:identity", passport.authenticate('jwt', { session: false }), (req, res) => {
  const identity = req.params.identity;
  if (identity == "user") {
    return res.send({
      code: -1,
      data: "权限不足"
    });
  }

  db.query(sql.selectUsers, (err, result) => {
    if (err) {
      res.send({
        status: 202,
        data: "查找失败,原因：" + err
      });
    } else {
      res.send({
        status: 200,
        data: result
      });
    }
  });
});

// 根据id查询用户
router.get("/getUser/:id", passport.authenticate('jwt', { session: false }), (req, res) => {
  db.query(sql.selectUserId + req.params.id, (err, result) => {
    if (err) throw err;
    if (result.length < 1) {
      return res.send({
        status: -1,
        data: "用户不存在"
      });
    }
    res.send({
      status: 200,
      data: result
    });
  });
});

// 注册
router.post("/register", (req, res) => {
  // 需要存进sql的数据
  const avatar = gravatar.url(req.body.email, { s: "200", r: "pg", d: "mm" });
  const user = {
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    avatar,
    identity: req.body.identity,
    createTime: new Date()
  };

  // 查询邮箱是否已经被注册
  db.query(`${sql.selectEmail}'${user.email}'`, (err, result) => {
    if (err) throw err;
    if (result[0]) {
      res.send({
        status: -1,
        data: "邮箱已存在！"
      });
    } else {
      // 密码加密
      bcrypt.genSalt(10, function (err, salt) {
        bcrypt.hash(user.password, salt, function (err, hash) {
          if (err) throw err;
          user.password = hash;

          // 问号防止sql注入
          // 将数据存到数据库
          db.query(sql.registerStorage, user, (err, result) => {
            if (err) throw err;
            res.send({
              status: 200,
              data: "注册成功"
            });
          });
        });
      });
    }
  });
});

// 登录
router.post("/login", (req, res) => {
  const user = {
    email: req.body.email,
    password: req.body.password
  };
  // 查询邮箱
  db.query(`${sql.selectEmail}'${user.email}'`, (err, result) => {
    if (err) throw err;
    if (!result[0]) {
      res.send({
        status: -9,
        data: "用户不存在"
      });
    } else {
      // 密码加密
      bcrypt.compare(user.password, result[0].password).then(isMatch => {
        if (isMatch) {
          const rule = { id: result[0].id, name: result[0].name };
          jwt.sign(rule, keys.secretOrKey, { expiresIn: 3600 }, (err, token) => {
            if (err) throw err;
            res.json({
              status: 200,
              data: "Bearer " + token
            });
          });
        } else {
          res.json({
            status: -1,
            data: "密码错误"
          });
        }
      });
    }
  });
});

module.exports = router;